package com.mock.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DBU {
    private static DruidDataSource ds;
    private static Properties p = new Properties();
    private static ThreadLocal<Connection> th = new ThreadLocal();

    static{
        try {
            p.load(DBU.class.getClassLoader().getResourceAsStream("com/mock/db.properties"));
            ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(p);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        if(th.get() == null){
            Connection connection = ds.getConnection();
            connection.setAutoCommit(false);
            th.set(connection);
            return connection;
        }else{
            return th.get();
        }
    }

    public static void begin() throws SQLException {
        getConnection().beginRequest();
    }

    public static void commit() throws SQLException {
        getConnection().commit();
    }

    public static void rollback() throws SQLException {
        getConnection().rollback();
    }

}
